package com.smart.manager.system.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alicp.jetcache.Cache;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.system.entities.body.RSystemConfig;
import com.smart.manager.system.entities.models.SystemConfig;
import com.smart.manager.system.entities.models.query.QSystemConfig;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Log4j2
@RequiredArgsConstructor
public class ConfigRepository {


    public Page<SystemConfig> pageList(RSystemConfig.SearchBody search) {
        QSystemConfig query = new QSystemConfig();
        Opt.ofBlankAble(search.getCode()).ifPresent(x -> query.code.contains(x));
        Opt.ofBlankAble(search.getTitle()).ifPresent(x -> query.title.contains(x));
        Opt.ofNullable(search.getState()).ifPresent(x -> query.state.eq(x));
        query.order().sort.asc().order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<SystemConfig>().load(query.findPagedList());
    }

    public void add(RSystemConfig.EditBody body) {
        QSystemConfig query = new QSystemConfig();
        SystemConfig record = query.code.eq(body.getCode()).setMaxRows(1).findOne();
        Assert.isNull(record, "创建失败:, 配置代码已存在");
        BeanUtil.copyProperties(body, SystemConfig.class).save();


    }


    public void update(Long id, RSystemConfig.EditBody body) {
        QSystemConfig query = new QSystemConfig();
        SystemConfig record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
        //刷新缓存
        refreshCache(body.getCode());
    }

    public int delByIds(List<Long> ids) {
        List<SystemConfig> list = new QSystemConfig().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        //刷新缓存
        list.forEach(item -> refreshCache(item.getCode()));
        return DB.deleteAll(list);

    }


    private final CacheService cacheService;

    public JSONObject readCache(String code) {
        Cache<String, JSONObject> configCache = cacheService.getConfigCache();
        JSONObject jsonObject = configCache.get(code);
        if (ObjectUtil.isNotNull(jsonObject)) {
            return jsonObject;
        }
        SystemConfig record = new QSystemConfig().code.eq(code).setMaxRows(1).findOne();
        Assert.notNull(record, code + "缓存参数查询失败");
        Assert.notEmpty(record.getItems(), record.getTitle() + "参数配置为空");
        JSONObject res = new JSONObject();
        record.getItems().forEach(x -> res.put(x.getCode(), x.getValue()));
        configCache.put(code, res);
        return res;
    }


    /**
     * 批量刷新缓存
     *
     * @param code 代码
     */
    private void refreshCache(String code) {
        Cache<String, JSONObject> configCache = cacheService.getConfigCache();
        configCache.remove(code);
    }


    /**
     * 批量刷新缓存
     *
     * @param ids id
     */
    public void batchRefreshCache(List<Long> ids) {
        new QSystemConfig().id.in(ids).findEach(item -> refreshCache(item.getCode()));
    }
}
